package com.yangli.leecode.a;

/**
 * @author ly
 * @description#https://leetcode-cn.com/problems/string-to-integer-atoi/ 请你来实现一个 myAtoi(string s) 函数，使其能将字符串转换成一个 32 位有符号整数（类似 C/C++ 中的 atoi 函数）。
 * @data 2022/4/22
 */
public class MyAtoi {
    public static void main(String[] args) {
        MyAtoi myAtoi = new MyAtoi();
        System.out.println(myAtoi.myAtoi("0  123"));
        //00000-42a1234 0
        //"  0000000000012345678"  12345678
    }

    public int myAtoi(String s) {
        if (s.length() == 0) {
            return 0;
        }
        StringBuilder sb = new StringBuilder();
        char[] chars = s.toCharArray();
        boolean begin = false;
        boolean haveZero = false;
        boolean unsgin = false;
        for (int i = 0, j = chars.length; i < j; ++i) {
            if (!begin) {
                if (chars[i] == 32) {
                    if(haveZero){
                        break;
                    }
                    continue;
                }
                if (chars[i] == '-') {
                    if(haveZero){
                        break;
                    }
                    unsgin =true;
                    begin = true;
                    sb.append(chars[i]);
                    continue;
                }
                if (chars[i] == '+') {
                    if(haveZero){
                        break;
                    }
                    begin = true;
                    continue;
                }
                if (chars[i] == 48) {
                    haveZero = true;
                    continue;
                }
            }
            if (chars[i] <= 57 && chars[i] >= 48) {
                if (chars[i] == 48 && (sb.length() == 0||sb.toString().equals("-"))) {
                    continue;
                }
                if (!begin) {
                    begin = true;
                }
                sb.append(chars[i]);
            } else {
                break;
            }
        }
        if (sb.length() == 0) {
            return 0;
        }
        if (sb.toString().equals("-")) {
            return 0;
        }
        if(sb.length()>11){
            if(unsgin){
                return Integer.MIN_VALUE;
            }else {
                return Integer.MAX_VALUE;
            }
        }
        long temp = Long.parseLong(sb.toString());
        if (temp > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        }
        if (temp < Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        }
        return Integer.parseInt(sb.toString());
    }

}
